package cronCreationAndParse.cronParse.parseNextTime;


import cronCreationAndParse.holidayUtil.holiday.*;
import cronCreationAndParse.holidayUtil.holidaysFilterPattern.Criteria;
import cronCreationAndParse.holidayUtil.holidaysFilterPattern.CriteriaTeacher;
import cronCreationAndParse.holidayUtil.holidaysIteratorPattern.HolidayIterator;
import cronCreationAndParse.holidayUtil.holidaysIteratorPattern.HolidayRepository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 李朔
 * @version 1.0
 */
public class AvoidHolidayCronParseDecorator extends CronParseDecorator {
    //构造器
    public AvoidHolidayCronParseDecorator(CronSequenceGenerator decoratedCronParse) {
        super(decoratedCronParse);
    }
    @Override
    public Date next(Date date){
        while(true) {
            Date newDate = checkHoliday(date);
            if (date.compareTo(newDate) == 0) {
                return decoratedCronParse.next(date);
            } else {
                return decoratedCronParse.next(newDate);
            }
        }
    }

    //是否需要避开节假日
    private Date checkHoliday(Date date){
//        HolidayRepository holidays=new HolidayRepository();
        Criteria criteria=new CriteriaTeacher();
        List<Holiday> holidays=new ArrayList<>();
        holidays.add(HolidayFactory.getHoliday(SpringFestival.getSpringFestival()));
        holidays.add(HolidayFactory.getHoliday(TeacherFestival.getTeacherFestival()));
        holidays.add(HolidayFactory.getHoliday(TestFestival.getTestFestival()));
        HolidayRepository holidaysRepository=new HolidayRepository(criteria,holidays);
        for(HolidayIterator iterator = holidaysRepository.getHolidayIterator(); iterator.hasNext();){
            Holiday holiday=(Holiday) iterator.next();
            if(date.compareTo(holiday.getStartDate())>=0 && date.compareTo(holiday.getEndDate())<=0){
                //在节日时间内
                date=holiday.firstDayAfterFestival();
            }
        }
        return date;
    }
}
